
package biblio.service.book;


import biblio.dao.BookDAO;
import biblio.domain.Book;
import biblio.util.SourceName;
import java.io.Serializable;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


/**
 * Provides data to editing and deleting.
 * 
 * @author mephisto
 */
@ManagedBean(name = "bookList")
@ViewScoped
public class BookList implements Serializable
{
    public void remove()
    {
        Book tmp = allItems.get(currentBookIndex);
        bookService.delete(tmp);
        allItems.remove(tmp);
    }

    public void store()
    {
        bookService.update(editedBook);
        allItems.set(currentBookIndex, editedBook);
    }

    public List<Book> getAllItems()
    {
        synchronized (this)
        {
            if (allItems == null)
            {
                BookDAO bookDAO = (BookDAO)appContext.getBean("bookDAO");
                allItems = bookDAO.selectAll();
            }
        }
        return allItems;
    }

    public int getCurrentBookIndex()
    {
        return currentBookIndex;
    }

    public void setCurrentBookIndex(int currentBookIndex)
    {
        this.currentBookIndex = currentBookIndex;
    }

    public Book getEditedBook()
    {
        return editedBook;
    }

    public void setEditedBook(Book editedBook)
    {
        this.editedBook = editedBook;
    }

    public int getPage()
    {
        return page;
    }

    public void setPage(int page)
    {
        this.page = page;
    }

    public void setBookService(BookServiceImpl bookService)
    {
        this.bookService = bookService;
    }

    static
    {
        appContext = new ClassPathXmlApplicationContext( new String[] {
                SourceName.DAO_APPLICATION_CONTEXT
        });
    }


    private static final long serialVersionUID = -3832235132261771583L;
    private static ApplicationContext appContext;
    private static Logger log = Logger.getLogger(BookList.class);
    private int page = 1;
    private List<Book> allItems = null;
    private int currentBookIndex;
    private Book editedBook;
    @ManagedProperty(value="#{bookService}")
    private BookServiceImpl bookService;
}
